package config

import (
	"fmt"
	"gitee.com/crack007/goose"
	"gitee.com/crack007/goose/config"
	"net/url"
	"strings"
)

func InitRoute() *RouteListConfig {
	nodeType := "route"
	routeMap := config.GetStringMap(nodeType, nil)
	routeListConfig := NewRouteListConfig()
	if routeMap != nil {
		for routeName := range routeMap {
			routeUrl := config.GetString(fmt.Sprintf("%s.%s.url", nodeType, routeName), "")
			if routeUrl == "" {
				continue
			}
			urlParse, err := url.Parse(routeUrl)
			if err != nil {
				goose.GetLogger().Warn("url error-> %s", err.Error())
				continue
			}
			route := &RouteConfig{
				Name:     routeName,
				Url:      routeUrl,
				Path:     urlParse.Path,
				Method:   strings.ToUpper(config.GetString(fmt.Sprintf("%s.%s.method", nodeType, routeName), "")),
				Strategy: config.GetInt(fmt.Sprintf("%s.%s.strategy", nodeType, routeName), 1),
				Unit:     config.GetUint(fmt.Sprintf("%s.%s.unit", nodeType, routeName), 1000),
			}
			route.RejectConfig = &RejectConfig{
				Code:        config.GetInt(fmt.Sprintf("%s.%s.reject.code", nodeType, routeName), 429),
				Body:        config.GetString(fmt.Sprintf("%s.%s.reject.body", nodeType, routeName), ""),
				ContentType: config.GetString(fmt.Sprintf("%s.%s.reject.contenttype", nodeType, routeName), "application/json"),
			}
			routeListConfig.AddRoute(route)
		}
	}
	return routeListConfig
}
